<template>

  <el-row type="flex" class="my-background" justify="center">
    <el-col :xl="6" :lg="7" :sm="8" class="my-container">
      <div>
        <h2 class="my-title">后台管理系统</h2>
        <el-form ref="loginForm" :model="loginForm"
                 status-icon :rules="loginRules"
                 class="demo-ruleForm">
          <el-form-item prop="username">
            <span slot="label">
      	      <span class="my-label">账号</span>
            </span>
            <el-input type="text" v-model="loginForm.username"
                      autocomplete="off"
                      placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item prop="password">
            <span slot="label">
              <span class="my-label">密码</span>
            </span>
            <el-input type="password"
                      v-model="loginForm.password"
                      autocomplete="off"
                      placeholder="请输入密码"/>
          </el-form-item>
          <el-form-item prop="verifyCode">
            <span slot="label">
              <span class="my-label">验证码</span>
            </span>
            <el-input type="text"
                      v-model="loginForm.verifyCode"
                      autocomplete="off"
                      placeholder="请输入验证码"
                      maxlength="6"
                      @keyup.enter.native="submitForm('loginForm')">
              <el-image slot="append"
                        :src="imgCode.img"
                        @click="getImgCode"
                        class="img-code"/>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       @click="submitForm('loginForm')">提交
            </el-button>
            <el-button @click="resetForm('loginForm')">重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-col>
  </el-row>
</template>

<script>
export default {
  name: "loginAdmin",
  data(){
    let validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'));
      }
      callback();
    };
    let validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      }
      callback();
    };
    let validateVerifyCode = (rule,  value, callback) => {
      let pattern = /^[A-Za-z0-9]{4}$/;
      if (value ==='') {
        callback(new Error('请输入验证码'));
      }
      if (!pattern.test(value)) {
        console.log(value);
        console.log(pattern.test(value));
        callback(new Error('验证码格式错误，不为四位数字与字母组成'));
      }
      callback();
    };
    return {
      imgCode: {
        img: '',
        code: ''
      },

      loginForm: {
        username: "",
        password: "",
        verifyCode: "",
        token: ""
      },
      loginRules: {
        username: [
          { validator: validateAccount,trigger: 'blur' }
        ],
        password: [
          { validator: validatePassword,trigger: 'blur'}
        ],
        verifyCode: [
          { validator: validateVerifyCode,trigger:'blur'}
        ]
      }
    };
  },
  methods: {
    /**
     * 封装axios
     * @param api 请求的接口
     * @param jsonData
     * @returns {Promise<unknown>}
     */
    myAxios(api,jsonData) {
      const self = this;
      return new Promise((resolve, reject)=>{
        self.$axios({
          method: 'post',
          url: api,
          data: jsonData
        }).then((res)=>{
          resolve(res.data);
        }).catch(err=>{
          console.log("this ->" + err)
          console.log("this ->" +  err.date)
            reject('error');
        })
      })
    },

    submitForm(formName) {
      let url = 'api/login/verify/verifyAdminUser'
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post(url, this.loginForm)
              .then(res=>{
                if(res.data.code !== 200){
                  return false
                }
                const token = res.data.data.token;
                this.$store.commit("SET_TOKEN",token);
                this.$router.push("/adminHome")
              }).catch((e)=>{console.log(e)})
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    async getImgCode(){
      let json = {'userId': this.loginForm.username};
      let rep = await this
          .myAxios('api/login/imageCode',json)
      let data = rep.data;
      console.log(data);
      let format = 'data:image/png;base64,';
      this.imgCode.img = format+data.img;
      this.imgCode.code = data.code;
      this.loginForm.token = data.code;
    }
  },
  created(){
    this.getImgCode();
  }
}
</script>

<style scoped>


  .my-background{
    background: url("../../assets/images/backGround/adminBg.jpg");
    height: 100%;
    display: flex;
    align-items: center;
  }
  .my-title{
    text-align: center;
  }
  .my-label{
    font-weight: bold;
    color: #6a4a52;
  }
  .my-container{
    background: rgba(0,0,0,0.3);
    padding: 20px 20px;
    border-radius: 4px;

  }
  .img-code{
    width: 100px;
    height: 36px;
  }
</style>